package com.tcheung;

import com.tcheung.service.AnswerService;
import com.tcheung.service.QueryService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MRR(单例)
 *
 * @author: zhangteng
 * @time: 2015/1/3 14:28
 */
public class MRR {

    private static MRR instance = null;

    public static MRR getInstance(int queryCount) {
        if (instance == null) {
            instance = new MRR(queryCount);
        }
        return instance;
    }

    /**
     * 此方法必须在getInstance(int queryCount)之后调用
     *
     * @return
     */
    public static MRR getInstance() {
        return instance;
    }

    private MRR(int queryCount) {
        this.queryCount = queryCount;
    }

    private int queryCount;
    private Map<Integer, Integer> queryResultRankMap = new HashMap<Integer, Integer>();

    private QueryService queryService = QueryService.getInstance();
    private AnswerService answerService = AnswerService.getInstance();

    public void calRank(int queryNum) {
        List<Integer> answerList = queryService.getAnswer(queryNum);
        Integer answer = answerService.getAnswerByQueryNum(queryNum);
        for (int i = 0;i < answerList.size(); ++i) {
            Integer a = answerList.get(i);
            if (a.compareTo(answer) == 0) {
                queryResultRankMap.put(queryNum, i+1);
            }
        }
    }

    public Double calMRR() {
        Double mrr = 0.0;
        Double result = 0.0;
        for (int queryNum = 1; queryNum <= queryCount; ++queryNum) {
            if (queryResultRankMap.containsKey(queryNum)) {
                result += 1.0 / queryResultRankMap.get(queryNum);
            } else {
                result += 0.0;
            }
        }
        mrr = (1.0/queryCount) * result;
        return mrr;
    }

    public String getMRRStr() {
        StringBuilder sb = new StringBuilder();
        for (int queryNum = 1; queryNum <= queryCount; ++queryNum) {
            if (queryResultRankMap.containsKey(queryNum)) {
                sb.append("rank_" + queryNum + ": " + queryResultRankMap.get(queryNum));
            } else {
                sb.append("rank_" + queryNum + ": 0");
            }
            sb.append("\n");
        }
        sb.append("\n");
        sb.append("mrr: " + calMRR());
        return sb.toString();
    }
}
